<template>
  <div id="account">
    <h3>商品类别</h3>
    <div>
      <el-select v-model="status" style="margin-left: 10px">
        <el-option>全部</el-option>
        <el-option :value="0" label="显示启用类别">显示启用类别</el-option>
        <!-- <el-option :value="1" label="显示禁用类别">显示禁用类别</el-option> -->
      </el-select>
      <el-button
        type="primary"
        style="margin-left: 10px"
        @click="searchPage(1, 5)"
        >查询</el-button
      >
      <div style="float: right">
        <el-button type="primary" @click="dialogFormVisible = true"
          >新增</el-button
        >
        <el-button type="" @click="allUpdateSta()">禁用</el-button>
        <el-button type="primary" @click="allstartSta()">启用</el-button>
        <el-button type="" @click="reFlush()">刷新</el-button>
      </div>
    </div>
    <hr style="margin-top: 10px" />
    <div class="account-content" style="margin-top: 10px">
      <div>
        <el-table
          :data="treeData"
          style="width: 100%; margin-bottom: 20px"
          row-key="id"
          border
          default-expand-all
          :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column
            prop="categoryname"
            label="类别"
            width="200"
          ></el-table-column>
          <el-table-column prop="status" label="状态" width="150">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.status"
                active-color="#66b1ff"
                inactive-color="#c1c1c1"
                :active-value="0"
                :inactive-value="1"
                @change="updateSta(scope.row.status, scope.row.id)"
              ></el-switch>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200">
            <template slot-scope="scope">
              <el-button
                @click="handleClick(scope.row.id)"
                type="text"
                size="small"
                >删除</el-button
              >
              <el-button
                @click="updateType(scope.row.id)"
                type="text"
                size="small"
                >编辑</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <el-dialog
      width="400px"
      top="100px"
      title="新增商品类别"
      :visible.sync="dialogFormVisible"
    >
      <table>
        <tr>
          <td>上级分类</td>
          <td>
            <el-button @click="choose = true">请选择分类</el-button>
            <div v-show="choose">
              <el-tree
                ref="tree"
                :data="treeData"
                :props="defaultProps"
                node-key="id"
                show-checkbox
                check-strictly
                @check-change="handleCheckChange"
              >
              </el-tree>
            </div>
          </td>
        </tr>
        <br />
        <tr>
          <td>类别</td>
          <td><el-input v-model="categoryname"></el-input></td>
        </tr>
        <br />
        <tr>
          <td></td>
        </tr>
      </table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="flush()">取 消</el-button>
        <el-button type="primary" @click="insert()">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog
      width="400px"
      top="100px"
      title="修改商品类别"
      :visible.sync="chooseType"
    >
      <div>
        <table>
          <tr>
            <td>上级分类</td>
            <td>
              <el-button @click="choose = true">请选择分类</el-button>
              <div v-show="choose">
                <el-tree
                  ref="tree"
                  :data="treeData"
                  :props="defaultProps"
                  node-key="id"
                  show-checkbox
                  check-strictly
                  @check-change="handleCheckChange"
                >
                </el-tree>
              </div>
            </td>
          </tr>
          <br />
          <tr>
            <td>类别</td>
            <td><el-input v-model="type.categoryname"></el-input></td>
          </tr>
          <br />
          <tr>
            <td></td>
          </tr>
        </table>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="flush1()">取 消</el-button>
        <el-button type="primary" @click="update()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "Account",
  data() {
    return {
      pageInfo: "",
      treeData: [],
      dialogFormVisible: false,
      status: "",
      multipleSelection: [],
      selectedids: [],
      chooseType: false,
      id: 0,
      categoryname: "",
      choose: false,
      selectedid: 0,
      defaultProps: {
        children: "children",
        label: "categoryname",
      },
      type: {
        id: "",
        categoryname: "",
        parentid: "",
      },
    };
  },
  methods: {
    insert: function () {
      if (this.categoryname === "") {
        alert("类别名称不能为空");
        return;
      }
      if (this.selectedid === null) {
        this.selectedid = 0;
      }
      const category = {
        id: this.id,
        parentid: this.selectedid,
        categoryname: this.categoryname,
      };
      this.axios({
        url: "/erp/goods/category/add",
        method: "POST",
        data: {
          ...category,
        },
      }).then((rs) => {
        console.log(rs.data.code === 200);
        if (rs.data.result == true) {
          this.choose = false;
          alert("新增成功");
          this.selectedid = 0;
          this.categoryname = "";
          this.flush();
          this.flush1();
        } else {
          alert("类别已存在");
        }
      });
    },

    handleClick: function (id) {
      if (!confirm("是否确认删除id位" + id + "的类别吗")) {
        return;
      }

      this.axios({
        url: "/erp/goods/category/del",
        params: {
          id: id,
        },
      }).then((rs) => {
        console.log(rs.data.result);
        if (rs.data.result == true) {
          this.searchPage();
        } else {
          alert("该用户下有子类，无法删除");
        }
      });
    },
    updateType: function (id) {
      this.id = id;
      this.chooseType = true;
      this.axios({
        url: "/erp/goods/category/getCategory",
        params: {
          id: id,
        },
      }).then((rs) => {
        this.type = rs.data.category;
        console.log("myType", this.type);
      });
    },
    update: function () {
      if (this.type.categoryname === "") {
        alert("类别不能为空");
        return;
      }
      if (this.selectedid === null) {
        this.selectedid = 0;
      }
      const category = {
        id: this.id,
        parentid: this.selectedid,
        categoryname: this.type.categoryname,
      };
      console.log(category);
      this.axios({
        url: "/erp/goods/category/update",
        method: "POST",
        data: {
          ...category,
        },
      }).then((rs) => {
        if (rs.data.code === 200) {
          this.dialogFormVisible = false;
          alert("修改成功");
          this.flush();
          this.flush1();
        } else {
          alert("类别已存在");
        }
      });
    },
    handleCheckChange(node, checked) {
      // 如果取消勾选，则不进行操作
      if (checked) {
        // 取消勾选其他所有节点
        const allCheckedNodes = this.$refs.tree.getCheckedNodes();
        allCheckedNodes.forEach((checkedNode) => {
          if (checkedNode.id !== node.id) {
            this.$refs.tree.setChecked(checkedNode, false);
          }
        });
        // 设置当前勾选节点的 id
        this.selectedid = node.id;
        console.log(this.selectedid);
      } else {
        // 如果节点被取消勾选，重置 selectedid
        this.selectedid = null;
      }
    },
    // 用于初始化或重置 selectedid
    // resetChecked() {
    //   this.selectedid = null;
    //   this.$refs.tree.setCheckedKeys([]);
    // },
    reFlush: function () {
      window.location.reload();
    },
    allstartSta: function () {
      console.log(this.multipleSelection);
      if (
        !Array.isArray(this.multipleSelection) ||
        this.multipleSelection.length === 0
      ) {
        return;
      }
      var ids = [];
      this.multipleSelection.forEach((item) => {
        ids.push(item.id);
      });
      this.axios.post("/erp/goods/category/openAllStatus", ids).then((rs) => {
        this.searchPage();
        this.multipleSelection = [];
      });
    },
    allUpdateSta: function () {
      if (
        !Array.isArray(this.multipleSelection) ||
        this.multipleSelection.length === 0
      ) {
        return;
      }
      var ids = [];
      this.multipleSelection.forEach((item) => {
        ids.push(item.id);
      });
      this.axios.post("/erp/goods/category/shutAllStatus", ids).then((rs) => {
        this.searchPage();
        this.multipleSelection = [];
      });
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    updateSta: function (status, id) {
      const category = {
        status: status,
        id: id,
      };
      console.log("lastCategory", category);
      this.axios({
        url: "/erp/goods/category/update",
        method: "POST",
        data: {
          ...category,
        },
      }).then((rs) => {
        console.log(rs.data.result);
        this.searchPage();
      });
    },
    flush: function () {
      this.dialogFormVisible = false;
      this.searchPage();
    },
    flush1: function () {
      this.chooseType = false;
      this.searchPage();
    },
    buildTree(data) {
      const tree = [];
      const map = {};

      // 将所有节点添加到map中，方便后续查找
      data.forEach((item) => {
        map[item.id] = { ...item, children: [] };
      });

      // 构建树形结构
      data.forEach((item) => {
        if (item.parentid === 0) {
          tree.push(map[item.id]);
        } else {
          if (map[item.parentid]) {
            map[item.parentid].children.push(map[item.id]);
          }
        }
      });

      return tree;
    },
    searchPage: function () {
      this.axios({
        url: "/erp/goods/category/getList",
        params: {
          status: this.status,
        },
      })
        .then((rs) => {
          // this.resetChecked();
          this.pageInfo = rs.data.list;
          console.log("list", rs.data.list);
          this.treeData = this.buildTree(this.pageInfo);
        })
        .catch((error) => {
          console.log(error);
        });
    },
  },
  created: function () {
    this.searchPage();
  },
};
</script>

<style scoped>
#account {
  width: 100%;
  height: 100%;
}

.account-top {
  width: calc(100% -20px);
  height: 60px;
  /* background-color: pink; */
  line-height: 60px;
  padding-left: 20px;
  font-size: 13px;
}

.account-top h3 {
  display: inline-block;
  margin-right: 1000px;
}

.account-content {
  width: 100%;
  height: calc(100% - 60px);
  /* background-color: skyblue; */
}

.el-input,
.el-button {
  font-size: 13px;
}
</style>